package com.zhiyou100.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.exceptions.ClientException;
import com.zhiyou100.dao.UserDao;
import com.zhiyou100.exception.LoginException;
import com.zhiyou100.model.User;
import com.zhiyou100.util.DateUtil;
import com.zhiyou100.util.SMSUtil;





@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDao;
	
	@Override
	public User getUserByPhoneAndId(String phone, Integer id) {

		User user = userDao.getUserByPhoneAndId(phone, id);
			
			
		
		return user;
	}

	@Override
	public void updateUserById(User user) {
		userDao.updateUserById(user);
		
	}

	@Override
	public int sendCode(String phone) {
		User user = userDao.getCodeByPhone(phone);
		Long threeMinut = DateUtil.drationFromNowTo(user.getCodeSendTime());
		if(threeMinut <180){
			throw new LoginException(403001,"抱歉，三分钟内不能重复发短信");
		}
		
		//发短信        (int)(Math.random()*(n-m+1))+m
		int code = (int)( Math.random() * (999999-100000+1) )+100000;
		
			try {
				SMSUtil.sendSMS(phone, code);
			} catch (ClientException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		
		if(user == null){
			//更具当前时间戳自动添加发短信时间
			userDao.save(phone, code);
		}else{
			//获取当前时间并更改数据库中的时间
			Date now = new Date();
			userDao.update(phone, code, now);
		}
			
				return code;
			
	}

	@Override
	public User loginByPhoneAndCode(String phone, int code) {
User saveuser = userDao.getCodeByPhone(phone);
		
		if(saveuser == null){
			
			throw new LoginException(403002, "手机号输入有误或用户未注册");
			
			
		}
		
		
		Long fiveMinut = DateUtil.drationFromNowTo(saveuser.getCodeSendTime());
		if(fiveMinut>300){
			throw new LoginException(403003,"验证码失效");
		}else if(!saveuser.getCode().equals(code)){
			throw new LoginException(403004,"验证码输入有误");
		}
		
		if(saveuser.getName() == null){
			int name0 = (int)( Math.random() * (999999-100000+1) )+100000;
			//随机生成一个昵称
			String name =String.valueOf(name0);
			userDao.addName(saveuser.getId(), saveuser.getPhone(), name);
			
			
		}
	
		return saveuser;
	}


	@Override
	public User loginByPhoneAndPassword(String phone, String password) {
		
		User saveuser = userDao.getCodeByPhone(phone);
		if(saveuser.getPassword() == null){
			throw new LoginException(403006, "帐号、密码错误或第三方登录未绑定手机号");
			
		}if(!saveuser.getPassword().equals(password)){
			throw new LoginException(403007, "密码错误");
			
		}
		
		
		return saveuser;
	}


	

}